import { TemplateConfig } from './../../services/print.const';
import { Component, Input } from '@angular/core';
import { ModalController, ToastController, LoadingController } from '@ionic/angular';
import { Global } from 'src/app/services/global.service';
import { LocalStorage } from 'src/app/services/local-storage.service';
import { BluetoothPrinterService } from 'src/app/services/bluetooth-printer.service';
import { SelectDevicePage } from '../select-device/select-device.page';

@Component({
	selector: 'app-template-detail',
	templateUrl: './template-detail.page.html',
	styleUrls: ['./template-detail.page.scss'],
})
export class TemplateDetailPage {

	@Input() config: TemplateConfig;

	constructor(
		private modalCtrl: ModalController,
		private toastCtrl: ToastController,
		private bluetoothPrinterService: BluetoothPrinterService,
		private global: Global
	) {

	}

	async dismiss() {
		await this.modalCtrl.dismiss();
	}

	private async toast(message: string) {
		const toast = await this.toastCtrl.create({
			message,
			duration: 3000
		});
		await toast.present();
	}


	translate(key: string) {
		return this.global.translate(key);
	}

	async connectDevice() {
		const modal = await this.modalCtrl.create({
			swipeToClose: true,
			presentingElement: await this.modalCtrl.getTop(),
			component: SelectDevicePage
		});

		await modal.present();
	}

	async print() {
		for (const item of this.config.configs) {
			if (!item.value && item.type !== 'feed') {
				this.toast(item.label + this.translate("NO_TEMPLATE_VALUE"))
				return;
			}
		}
		const device = this.bluetoothPrinterService.getDevice();
		if (!device.id) {
			this.toast(this.translate("CONNECT_DEVICE_FIRST"))
			this.connectDevice();
		} else {
			this.bluetoothPrinterService.print(this.config.configs);
		}
	}

}
